import React, { useState, useEffect, useCallback } from 'react';
import {
  Container,
  Typography,
  Paper,
  Box,
  Grid,
  Card,
  CardContent,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  CircularProgress,
  Alert,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions
} from '@mui/material';

const Account = ({ user }) => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [userData, setUserData] = useState(null);
  const [transactions, setTransactions] = useState([]);
  const [collectDialogOpen, setCollectDialogOpen] = useState(false);
  const [selectedTransaction, setSelectedTransaction] = useState(null);
  const [repayDialogOpen, setRepayDialogOpen] = useState(false);
  const [warningDialogOpen, setWarningDialogOpen] = useState(false);
  const [warningMessage, setWarningMessage] = useState('');

  // 获取用户信息和交易历史
  const fetchUserData = useCallback(async () => {
    try {
      setLoading(true);
      // 获取用户信息
      const userResponse = await fetch(`http://localhost:3001/api/user/${user.id}`);
      const userData = await userResponse.json();

      if (userData.success) {
        setUserData(userData.user);
      }

      // 获取交易历史
      const transactionsResponse = await fetch(`http://localhost:3001/api/transactions/${user.id}`);
      const transactionsData = await transactionsResponse.json();

      if (transactionsData.success) {
        setTransactions(transactionsData.transactions);
      }

      setLoading(false);
    } catch (err) {
      console.error('获取用户数据失败:', err);
      setError('获取用户数据失败');
      setLoading(false);
    }
  }, [user?.id]);

  useEffect(() => {
    if (user) {
      fetchUserData();
    }
  }, [user, fetchUserData]);

  const handleCollect = async (transaction) => {
    try {
      const response = await fetch('http://localhost:3001/api/collect-loan', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          userId: user.id,
          transactionId: transaction.id
        }),
      });

      const data = await response.json();

      if (data.success) {
        setSuccess('收回贷款成功！');
        setCollectDialogOpen(false);
        // 刷新数据
        fetchUserData();
      } else {
        if (data.message === '贷款未到期，不能收回') {
          setWarningMessage(`贷款未到期，不能收回。\n到期时间：${new Date(data.dueDate).toLocaleString()}\n剩余天数：${data.remainingDays}天`);
          setWarningDialogOpen(true);
        } else {
          setError(data.message || '收回贷款失败');
        }
      }
    } catch (err) {
      setError('网络错误，请稍后重试');
    }
  };

  const handleConfirmCollect = async () => {
    try {
      const response = await fetch('http://localhost:3001/api/collect-loan', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          userId: user.id,
          transactionId: selectedTransaction.id
        }),
      });

      const data = await response.json();

      if (data.success) {
        setSuccess('收回贷款成功！');
        setCollectDialogOpen(false);
        // 刷新数据
        fetchUserData();
      } else {
        setError(data.message || '收回贷款失败');
      }
    } catch (err) {
      setError('网络错误，请稍后重试');
    }
  };

  const handleRepay = (transaction) => {
    setSelectedTransaction(transaction);
    setRepayDialogOpen(true);
  };

  const handleConfirmRepay = async () => {
    try {
      const response = await fetch('http://localhost:3001/api/repay', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          userId: user.id,
          loanId: selectedTransaction.id
        }),
      });

      const data = await response.json();

      if (data.success) {
        setSuccess(`还款成功！信用分${data.scoreChange > 0 ? '增加' : '减少'}${Math.abs(data.scoreChange)}分`);
        setRepayDialogOpen(false);
        // 刷新数据
        fetchUserData();
      } else {
        setError(data.message || '还款失败');
      }
    } catch (err) {
      setError('网络错误，请稍后重试');
    }
  };

  if (!user) {
    return (
      <Container maxWidth="md" sx={{ mt: 4 }}>
        <Alert severity="warning">请先登录</Alert>
      </Container>
    );
  }

  if (loading) {
    return (
      <Container maxWidth="md" sx={{ mt: 4, textAlign: 'center' }}>
        <CircularProgress />
      </Container>
    );
  }

  if (error) {
    return (
      <Container maxWidth="md" sx={{ mt: 4 }}>
        <Alert severity="error">{error}</Alert>
      </Container>
    );
  }

  return (
    <Container maxWidth="md" sx={{ mt: 4 }}>
      <Grid container spacing={3}>
        {/* 用户信息卡片 */}
        <Grid item xs={12}>
          <Card>
            <CardContent>
              <Typography variant="h5" gutterBottom>
                账户信息
              </Typography>
              <Box sx={{ mt: 2 }}>
                <Typography variant="body1">
                  用户名：{userData?.username}
                </Typography>
                <Typography variant="body1" color="primary" sx={{ mt: 1 }}>
                  当前余额：{(userData?.balance || 0).toFixed(2)} 元
                </Typography>
                <Typography variant="body1" sx={{ mt: 1 }}>
                  信用评分：{userData?.creditScore || 0}
                </Typography>
              </Box>
            </CardContent>
          </Card>
        </Grid>

        {/* 交易历史 */}
        <Grid item xs={12}>
          <Paper sx={{ p: 3 }}>
            <Typography variant="h5" gutterBottom>
              个人借款记录
            </Typography>
            {error && (
              <Alert severity="error" sx={{ mb: 2 }}>
                {error}
              </Alert>
            )}
            {success && (
              <Alert severity="success" sx={{ mb: 2 }}>
                {success}
              </Alert>
            )}
            <TableContainer>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>时间</TableCell>
                    <TableCell>金额</TableCell>
                    <TableCell>到期时间</TableCell>
                    <TableCell>状态</TableCell>
                    <TableCell>操作</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {transactions
                    .filter(t => t.type === 'loan' && t.toUserId === parseInt(user.id))
                    .map((transaction) => (
                      <TableRow key={transaction.id}>
                        <TableCell>
                          {new Date(transaction.timestamp).toLocaleString()}
                        </TableCell>
                        <TableCell>{transaction.amount} 元</TableCell>
                        <TableCell>
                          {new Date(transaction.dueDate).toLocaleString()}
                        </TableCell>
                        <TableCell>
                          {transaction.status === 'pending' ? '进行中' : '已完成'}
                        </TableCell>
                        <TableCell>
                          {transaction.status === 'pending' && (
                            <Button
                              variant="contained"
                              color="primary"
                              size="small"
                              onClick={() => handleRepay(transaction)}
                            >
                              还款
                            </Button>
                          )}
                        </TableCell>
                      </TableRow>
                    ))}
                  {transactions.filter(t => t.type === 'loan' && t.toUserId === parseInt(user.id)).length === 0 && (
                    <TableRow>
                      <TableCell colSpan={5} align="center">
                        暂无借款记录
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </TableContainer>
          </Paper>
        </Grid>

        {/* 放贷记录 */}
        <Grid item xs={12}>
          <Paper sx={{ p: 3 }}>
            <Typography variant="h5" gutterBottom>
              个人放贷记录
            </Typography>
            <TableContainer>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>时间</TableCell>
                    <TableCell>本金</TableCell>
                    <TableCell>利率</TableCell>
                    <TableCell>到期总额</TableCell>
                    <TableCell>到期时间</TableCell>
                    <TableCell>状态</TableCell>
                    <TableCell>操作</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {transactions
                    .filter(t => t.type === 'lend' && t.fromUserId === parseInt(user.id))
                    .map((transaction) => (
                      <TableRow key={transaction.id}>
                        <TableCell>
                          {new Date(transaction.timestamp).toLocaleString()}
                        </TableCell>
                        <TableCell>{transaction.amount} 元</TableCell>
                        <TableCell>{transaction.interestRate}%</TableCell>
                        <TableCell>{transaction.totalAmount?.toFixed(2)} 元</TableCell>
                        <TableCell>
                          {new Date(transaction.dueDate).toLocaleString()}
                        </TableCell>
                        <TableCell>
                          {transaction.status === 'pending' ? '进行中' : '已完成'}
                        </TableCell>
                        <TableCell>
                          {transaction.status === 'pending' && (
                            <Button
                              variant="contained"
                              color="primary"
                              size="small"
                              onClick={() => handleCollect(transaction)}
                            >
                              收回
                            </Button>
                          )}
                        </TableCell>
                      </TableRow>
                    ))}
                  {transactions.filter(t => t.type === 'lend' && t.fromUserId === parseInt(user.id)).length === 0 && (
                    <TableRow>
                      <TableCell colSpan={7} align="center">
                        暂无放贷记录
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </TableContainer>
          </Paper>
        </Grid>
      </Grid>

      {/* 收回贷款确认对话框 */}
      <Dialog open={collectDialogOpen} onClose={() => setCollectDialogOpen(false)}>
        <DialogTitle>确认收回贷款</DialogTitle>
        <DialogContent>
          <Typography>
            您确定要收回贷款吗？
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
            本金：{selectedTransaction?.amount} 元
          </Typography>
          <Typography variant="body2" color="text.secondary">
            利率：{selectedTransaction?.interestRate}%
          </Typography>
          <Typography variant="body2" color="text.secondary">
            到期总额：{selectedTransaction?.totalAmount?.toFixed(2)} 元
          </Typography>
          <Typography variant="body2" color="text.secondary">
            到期时间：{selectedTransaction?.dueDate ? new Date(selectedTransaction.dueDate).toLocaleString() : ''}
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setCollectDialogOpen(false)}>取消</Button>
          <Button
            onClick={handleConfirmCollect}
            variant="contained"
            color="primary"
          >
            确认收回
          </Button>
        </DialogActions>
      </Dialog>

      {/* 还款确认对话框 */}
      <Dialog open={repayDialogOpen} onClose={() => setRepayDialogOpen(false)}>
        <DialogTitle>确认还款</DialogTitle>
        <DialogContent>
          <Typography>
            您确定要还款吗？
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
            还款金额：{selectedTransaction?.amount} 元
          </Typography>
          <Typography variant="body2" color="text.secondary">
            到期时间：{selectedTransaction?.dueDate ? new Date(selectedTransaction.dueDate).toLocaleString() : ''}
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setRepayDialogOpen(false)}>取消</Button>
          <Button
            onClick={handleConfirmRepay}
            variant="contained"
            color="primary"
          >
            确认还款
          </Button>
        </DialogActions>
      </Dialog>

      {/* 警告对话框 */}
      <Dialog open={warningDialogOpen} onClose={() => setWarningDialogOpen(false)}>
        <DialogTitle>提示</DialogTitle>
        <DialogContent>
          <Typography>
            {warningMessage}
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setWarningDialogOpen(false)}>确定</Button>
        </DialogActions>
      </Dialog>
    </Container>
  );
};

export default Account; 